package com.server.app;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.ideawedo.http.tools.HttpConfig;
import com.ideawedo.orm.tools.DatabaseConfig;
import com.server.protocols.HProtocols;
import com.server.protocols.SProtocols;
import com.server.server.BroadcastServer;
import com.server.server.EntryGameServer;
import com.server.server.GetPlayerDataServer;
import com.server.server.HeartBeatServer;
import com.server.server.JoinRoomServer;
import com.server.server.LeaveRoomServer;
import com.server.server.LoadedGameServer;
import com.server.server.MatchRoomServer;
import com.server.server.ReadyGameServer;
import com.server.timertask.LmyScheduledTask;
import com.server.tools.GameConfig;
import com.webserver.server.net.BaseServer;
import com.webserver.server.net.ServerManager;

/**
* @author	李小布
* @email	397554852@qq.com
* @version	创建时间：2018年11月27日 下午4:34:12
*/
public class GameWorld {
	private static GameWorld instance;

	public static GameWorld GetInstance(){
		if(instance == null){
			instance = new GameWorld();
		}
		return instance;
	}

	private ServerManager server;

	public void StartGame(){
		try{
			try {
				GameConfig.load();
				
				//网络服务 端口号
				server = new ServerManager(GameConfig.socket_port);
				server.Start();
				//注册游戏业务服务
				server.setServerList(RegistServer());
				HttpConfig.init(HProtocols.GetMap());
				DatabaseConfig.init();
				
				LmyScheduledTask DayPlay = new LmyScheduledTask(null,"DayPlan",0,9,0,0);
				DayPlay.Start();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			//启动游戏
			Start();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void Start(){
		new MainLoop().start();
	}
	
	/**
	 * 游戏主线程
	 * 
	 */
	public class MainLoop extends Thread {
		@Override
		public void run() {
			while (true) {
				try {
					// 游戏逻辑
					GameTick();
					//线程休眠60s
					Thread.sleep(60000);
				} catch (Exception e) {
					System.out.println("error in MainLoop tick ");
					e.printStackTrace();
				}
			}
		}

		/**
		 * 游戏逻辑
		 */
		public void GameTick() {
		}
	}
	
	Map<Integer,BaseServer> RegistServer(){

		Map<Integer,BaseServer> servermap = new HashMap<Integer,BaseServer>();

		servermap.put(SProtocols.ENTRY_GAME, new EntryGameServer());
		servermap.put(SProtocols.LOGOUT_GAME, new EntryGameServer());
		servermap.put(SProtocols.HEART_BEAT, new HeartBeatServer());
		servermap.put(SProtocols.MATCH_ROOM, new MatchRoomServer());
		servermap.put(SProtocols.JOIN_ROOM, new JoinRoomServer());
		servermap.put(SProtocols.LEAVE_ROOM, new LeaveRoomServer());
		servermap.put(SProtocols.READY_GAME, new ReadyGameServer());
		servermap.put(SProtocols.LOADED_GAME, new LoadedGameServer());
		servermap.put(SProtocols.SEBROADCAST, new BroadcastServer());
		servermap.put(SProtocols.GET_PLAYERS, new GetPlayerDataServer());
		return servermap;
	}
}